import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function GET(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const conversations = await prisma.conversation.findMany({
      where: {
        participants: {
          some: {
            userId: userId,
          },
        },
      },
      include: {
        participants: {
          include: {
            user: {
              select: {
                id: true,
                username: true,
                avatar: true,
              },
            },
          },
        },
        messages: {
          orderBy: {
            createdAt: 'desc',
          },
          take: 1,
          include: {
            sender: {
              select: {
                username: true,
              },
            },
          },
        },
      },
      orderBy: {
        updatedAt: 'desc',
      },
    });

    const formattedConversations = conversations.map((conv: any) => {
      const lastMessage = conv.messages[0];
      const unreadCount = Math.floor(Math.random() * 5); // 随机生成0-4的未读数
      if (conv.type === 'private') {
        const otherParticipant = conv.participants.find((p: any) => p.userId !== userId)?.user;
        return {
          id: conv.id,
          type: 'private',
          name: otherParticipant?.username,
          avatar: otherParticipant?.avatar,
          friend: otherParticipant,
          participants: conv.participants.map((p: any) => p.user),
          lastMessage: lastMessage ? {
            content: lastMessage.content,
            createdAt: lastMessage.createdAt,
            sender: {
              username: lastMessage.sender.username,
            },
          } : null,
          unreadCount,
        };
      } else { // group
        return {
          id: conv.id,
          type: 'group',
          name: conv.name,
          avatar: conv.avatar,
          participants: conv.participants.map((p: any) => p.user),
          lastMessage: lastMessage ? {
            content: lastMessage.content,
            createdAt: lastMessage.createdAt,
            sender: {
              username: lastMessage.sender.username,
            },
          } : null,
          unreadCount,
        };
      }
    });

    return NextResponse.json(formattedConversations);

  } catch (error) {
    console.error('获取会话列表失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { targetUserId } = await req.json();
    if (!targetUserId) {
      return NextResponse.json({ error: '目标用户ID不能为空' }, { status: 400 });
    }

    // 查找是否已存在这两个用户的私聊会话
    const existingConversation = await prisma.conversation.findFirst({
      where: {
        type: 'private',
        participants: {
          every: {
            userId: {
              in: [userId, targetUserId],
            },
          },
        },
      },
    });

    if (existingConversation) {
      return NextResponse.json(existingConversation);
    }

    // 如果不存在，则创建新会话
    const newConversation = await prisma.conversation.create({
      data: {
        type: 'private',
        participants: {
          create: [
            { userId: userId },
            { userId: targetUserId },
          ],
        },
      },
    });

    return NextResponse.json(newConversation, { status: 201 });

  } catch (error) {
    console.error('创建会话失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 